package com.wzk.travelspringboot.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.RandomUtil;
import com.wzk.travelspringboot.common.LogToFile;
import com.wzk.travelspringboot.common.RedisConstant;
import com.wzk.travelspringboot.dto.ChangePasswordDTO;
import com.wzk.travelspringboot.dto.LoginDTO;
import com.wzk.travelspringboot.dto.RegisterDTO;
import com.wzk.travelspringboot.dto.Result;
import com.wzk.travelspringboot.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * @Author: WangZiKang
 * @Date: 2025/1/4 22:10
 */
@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    private final StringRedisTemplate stringRedisTemplate;

    private final JavaMailSenderImpl javaMailSender;

    public static final Logger logger = Logger.getLogger(UserController.class.getName());

    //获取验证码图片
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletResponse response) throws IOException {
        try{
            //生成验证码图片
            CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 5, 30);
            String captchaCode = captcha.getCode();
            //缓存到redis 60s过期
            stringRedisTemplate.opsForValue().set(RedisConstant.CAPTCHA_CODE_KEY+captchaCode,captchaCode,RedisConstant.CAPTCHA_CODE_TIME, TimeUnit.SECONDS);
            //返回验证码图片
            captcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            response.getOutputStream().close();
        }
    }

    //用户登录
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDTO dto){
        return userService.login(dto);
    }

    //用户注册
    @PostMapping("/register")
    public Result register(@Validated @RequestBody RegisterDTO dto){
        return userService.register(dto);
    }

    //验证邮箱发送验证码
    @GetMapping("/mail/code")
    public Result mailCode(@Email(message = "邮箱不合法") String email){
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(),true);
            //邮件发信人
            mimeMessageHelper.setFrom("1750464197@qq.com");
            //邮件收信人
            mimeMessageHelper.setTo(email);
            //邮件主题
            mimeMessageHelper.setSubject("康旅账号注册验证码");
            //邮件内容
            String code = RandomUtil.randomNumbers(6);
            mimeMessageHelper.setText("【康旅】您的验证码是"+code+"，用于邮箱验证注册账户，5分钟内有效。验证码提供给他人可能导致账号被盗，请勿泄漏，谨防被骗！");
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            log.info("邮件发送成功！");
            //缓存验证码设置过期时间
            stringRedisTemplate.opsForValue().set(RedisConstant.EMAIL_CODE_KEY+email,code,RedisConstant.EMAIL_CODE_TIME,TimeUnit.MINUTES);
            return Result.success("验证码发送成功！",null);
        } catch (Exception e) {
            e.printStackTrace();
            LogToFile.logToFile("邮件验证码发送失败！出现："+e.getMessage(),logger,"email_send_err");
            return Result.failed("验证码发送失败！请重试");
        }
    }

    //修改用户头像
    @PostMapping("/change/avatar")
    @Validated
    public Result changeUserAvatar(
            @RequestParam("userId") @NotBlank(message = "用户id不能为空") String userId,
            @RequestParam("avatar") MultipartFile avatar
            ){
        return userService.changeAvatar(Long.valueOf(userId),avatar);
    }

    //修改用户密码
    @PostMapping("/change/pwd")
    public Result changeUserPassword(@Validated @RequestBody ChangePasswordDTO dto){
        return userService.changePwd(dto);
    }
}
